// miniprogram/pages/exam/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    question_list: [],
    current_index: 0,
    current_question: {},
    selected_options_id: '',
    exam_status: 'PENDING', // PENDING-准备中 GOING-考试中 END-考试结束 ERROR-网络异常
    exam_score: 0,
    exam_result: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetchExamPaper();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 获取试题
   */
  fetchExamPaper: function() {
    wx.cloud.callFunction({ name: 'fetchExamPaper' })
    .then(res => {
      const question_list = res.result || [];
      const current_index = 0;
      const current_question = question_list[current_index] || {};
      this.setData({ question_list, current_index, current_question, exam_status: 'GOING' });
    })
    .catch(err => {
      console.error('fetchExamPaper', err);
      this.setData({ exam_status: 'ERROR' });
    });
  },

  /**
   * 选中选项
   * @param {*} res 
   */
  onSelectAction: function (res) {
    const { question_list, current_index } = this.data;
    const { optionsId } = res.target.dataset;
    question_list[current_index].selected_options_id = optionsId;
    this.setData({ selected_options_id: optionsId });
    const timer = setTimeout(() => {
      const next_index = current_index + 1;
      if (next_index >= question_list.length) {
        this.calculateExamResult();
        clearTimeout(timer);
        return;
      }
      const next_question = question_list[next_index];
      this.setData({
        current_index: next_index,
        current_question: next_question,
        selected_options_id: '',
      });
      clearTimeout(timer);
    }, 600);
  },

  /**
   * 计算测验结果
   */
  calculateExamResult: function () {
    const { question_list } = this.data;
    const exam_result = [];
    let exam_score = 0;
    question_list.forEach(item => {
      const { title, options_list, score, selected_options_id } = item;
      const correct_opts_obj = options_list.find(opt => opt.is_right === 1 );
      const selected_opts_obj = options_list.find(opt => opt.id === selected_options_id );
      if (selected_opts_obj.is_right) exam_score += score;
      const e_result = { title, correct_options: correct_opts_obj, selected_options: selected_opts_obj, is_right: selected_opts_obj.is_right };
      exam_result.push(e_result);
    });
    this.setData({ exam_status: 'END', exam_score, exam_result });
  },

  /**
   * 重新测试
   */
  resetExamAction: function () {
    this.setData({
      exam_status: 'PENDING',
      exam_result: [],
      exam_score: 0,
      selected_options_id: '',
    });
    this.fetchExamPaper();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const { exam_score, exam_status } = this.data;
    let title = '我正在进行垃圾分类测试，你也来试试吧！';
    if (exam_status === 'END') {
      title = `我在垃圾分类测试中得了${exam_score}分，你能得多少分？`;
    }
    const path = '/pages/exam/index';
    return { title, path };
  }
})